package org.dromara.learning_xq.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.dromara.learning_xq.config.QiniuUtil;
import org.dromara.learning_xq.entity.AsTeachingMaterial;
import org.dromara.learning_xq.entity.dto.AsTeachingMaterialDto;
import org.dromara.learning_xq.service.AsTeachingMaterialService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/asTeachingMaterial")
@Tag(name = "教材内容")
public class AsTeachingMaterialController {

    @Autowired
    private AsTeachingMaterialService asteachingMaterialService;

    @Autowired
    private QiniuUtil qiniuUtil;


    private static final String UPLOAD_DIR = "lspsb/"; // 文件存储目录


    @PostMapping("/uploadAsTeachingMaterial")
    @Operation(summary = "增加教材内容")
    public ResponseEntity<String> addTeachingMaterial(
        @RequestParam("file") MultipartFile multipartFile,
        @RequestParam("contentId") Long contentId,
        @RequestParam("state") String state,
        @RequestParam("titleName") String titleName,
        @RequestParam("studyText") String studyText,
        @RequestParam("learningLevel") String learningLevel,
        @RequestParam("delFlag") String delFlag,
        @RequestParam("createBy") String createBy) {

        // 文件校验
        if (multipartFile.isEmpty()) {
            return new ResponseEntity<>("No file uploaded", HttpStatus.BAD_REQUEST);
        }

        try {
            // 上传文件到七牛云
            String fileUrl = qiniuUtil.uploadVideo(multipartFile);

            // 创建并保存教学材料对象
            AsTeachingMaterial asTeachingMaterial = new AsTeachingMaterial();
            asTeachingMaterial.setContentId(contentId);
            asTeachingMaterial.setState(state);
            asTeachingMaterial.setStudyText(studyText);
            asTeachingMaterial.setTitleName(titleName);
            asTeachingMaterial.setLearningLevel(learningLevel);
            asTeachingMaterial.setDelFlag(delFlag);
            asTeachingMaterial.setCreateBy(createBy);
            asTeachingMaterial.setVideo(fileUrl); // 使用七牛云返回的 URL

            int success = asteachingMaterialService.insertAsTeachingMaterial(asTeachingMaterial);

            if (success > 0) {
                return ResponseEntity.status(HttpStatus.CREATED).body("添加成功");
            } else {
                return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("添加失败");
            }
        } catch (Exception e) {
            // 处理异常
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("服务器错误");
        }
    }

    @PostMapping("/update")
    @Operation(summary = "更新教材内容")
    public ResponseEntity<String> updateTeachingMaterial(
        @RequestParam("id") Long id,
        @RequestParam(value = "file", required = false) MultipartFile multipartFile,
        @RequestParam("contentId") Long contentId,
        @RequestParam("state") String state,
        @RequestParam("titleName") String titleName,
        @RequestParam("studyText") String studyText,
        @RequestParam("learningLevel") String learningLevel,
        @RequestParam("delFlag") String delFlag,
        @RequestParam("createBy") String createBy) {

        // 查找要更新的教学材料对象
        AsTeachingMaterial existingMaterial = asteachingMaterialService.findById(id);

        if (existingMaterial == null) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body("Teaching material not found");
        }

        try {
            // 如果有文件上传，处理文件上传
            if (multipartFile != null && !multipartFile.isEmpty()) {
                // 上传文件到七牛云
                String fileUrl = qiniuUtil.uploadVideo(multipartFile);
                existingMaterial.setVideo(fileUrl); // 更新视频 URL
            }

            // 更新其他字段
            existingMaterial.setContentId(contentId);
            existingMaterial.setState(state);
            existingMaterial.setStudyText(studyText);
            existingMaterial.setTitleName(titleName);
            existingMaterial.setLearningLevel(learningLevel);
            existingMaterial.setDelFlag(delFlag);
            existingMaterial.setCreateBy(createBy);

            // 保存更新后的教学材料对象
            int updated = asteachingMaterialService.updateAsTeachingMaterial(existingMaterial);

            if (updated > 0) {
                return ResponseEntity.status(HttpStatus.OK).body("Update successful");
            } else {
                return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Update failed");
            }
        } catch (Exception e) {
            // 处理异常
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Server error: " + e.getMessage());
        }
    }

    @PostMapping("/selverAll")
    @Operation(summary = "查询所有教材内容")
    public ResponseEntity<?> selverAll(@RequestBody AsTeachingMaterialDto asTeachingMaterialDto) {
        try {
            List<AsTeachingMaterialDto> teachingMaterials = asteachingMaterialService.selverAll(asTeachingMaterialDto);

            if (teachingMaterials.isEmpty()) {
                return ResponseEntity.status(HttpStatus.NO_CONTENT).body("No teaching materials found.");
            }

            return ResponseEntity.ok(teachingMaterials);

        } catch (Exception e) {
            // 处理可能发生的异常
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("An error occurred while fetching teaching materials.");
        }
    }

    /**
     * 根据教材标题的部分信息进行模糊查询
     *
     * @param titleName 教材标题的部分字符串，为可选参数
     * @return 响应实体，包含查询结果或错误信息
     */
    @PostMapping("/selverFuzzyQuery")
    @Operation(summary = "模糊查询教材内容")
    public ResponseEntity<?> selverFuzzyQuery(@RequestParam(required = false) String titleName) {
        // 检查查询参数是否为空
        if (titleName == null || titleName.trim().isEmpty()) {
            return ResponseEntity.badRequest().body("标题名称不能为空");
        }

        try {
            // 调用服务层进行查询
            List<AsTeachingMaterialDto> teachingMaterials = asteachingMaterialService.selverFuzzyQuery(titleName);

            // 根据查询结果返回响应
            if (teachingMaterials.isEmpty()) {
                return ResponseEntity.status(HttpStatus.NO_CONTENT).body("找不到教材");
            }

            return ResponseEntity.ok(teachingMaterials);
        } catch (Exception e) {
            // 捕获并处理可能的异常
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("处理请求时出错");
        }
    }

    @PostMapping("/selverId")
    @Operation(summary = "根据ID查询教材内容")
    public ResponseEntity<?> selverId(@RequestParam Long id) {
        try {
            // 调用服务层方法，根据 ID 查询教材内容
            AsTeachingMaterialDto teachingMaterial = asteachingMaterialService.selverId(id);

            // 如果查询结果为空，返回 404 Not Found
            if (teachingMaterial == null) {
                return ResponseEntity.status(HttpStatus.NOT_FOUND).body("教材不存在");
            }

            // 如果查询结果存在，返回 200 OK 和结果
            return ResponseEntity.ok(teachingMaterial);
        } catch (Exception e) {
            // 处理异常情况，返回 500 Internal Server Error 和异常信息
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("服务器内部错误: " + e.getMessage());
        }
    }

    @PostMapping("/selverPaginationQuery")
    @Operation(summary = "分页查询教材内容")
    public ResponseEntity<?> selverPaginationQuery(
        @RequestParam int pageNum,
        @RequestParam int pageSize) {
        try {
            // 调用服务层方法，进行分页查询
            Page<AsTeachingMaterial> page = asteachingMaterialService.selverPaginationQuery(pageNum, pageSize);

            // 如果查询结果为空或没有数据，返回 404 Not Found
            if (page == null || page.getTotal() == 0) {
                return ResponseEntity.status(HttpStatus.NOT_FOUND).body("未找到记录。");
            }

            // 返回查询结果和分页信息
            return ResponseEntity.ok(page);
        } catch (Exception e) {
            // 捕获异常并返回 500 Internal Server Error
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                .body("处理请求时出错:" + e.getMessage());
        }
    }

    @PostMapping("/deleteId")
    @Operation(summary = "根据ID删除教材内容")
    public ResponseEntity<String> deleteId(@RequestParam Long id) {
        if (id == null || id <= 0) {
            // 参数校验失败，返回 400 Bad Request
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("无效的ID");
        }

        try {
            boolean deleted = asteachingMaterialService.removeId(id);

            if (deleted) {
                return ResponseEntity.ok("删除成功");
            } else {
                return ResponseEntity.status(HttpStatus.NOT_FOUND).body("教材内容不存在");
            }
        } catch (Exception e) {
            // 捕获并处理异常
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("删除操作失败");
        }
    }

}
